import * as selectService from "@/apis/selectService"
import * as downloadService from "@/apis/downloadService"
import * as previewService from "@/apis/previewService"
import * as operateService from "@/apis/operateService"
import {defineStore} from "pinia";
import {computed, ref, watch} from "vue";
import {ElLoading, ElMessage} from "element-plus";
import * as uploadService from "@/apis/uploadService"
import {serverPath} from "@/utils/path";


export const homeStore = defineStore('home', () => {
    const tableData = ref([])
    const currentPath = ref("")
    const uploadPath = ref("")
    const pathCrumbs = ref([])
    const searchName = ref("")
    const rightRow = ref(null)
    const rename = ref("")
    const uploadFileList = []
    if (localStorage.getItem("searchMaxSize") === null) {
        localStorage.setItem("searchMaxSize", "1000");
    }
    const searchMaxSize = ref(parseInt(localStorage.getItem("searchMaxSize")))

    const loading = ref(false)
    let load = 0


    watch(searchMaxSize, (newSearchMaxSize) => {
        localStorage.setItem("searchMaxSize", newSearchMaxSize.toString());
    });

    async function downloadFiles(paths){
        // 创建一个虚拟的 <a> 元素
        const link = document.createElement('a');
        // 设置下载链接的 href 属性
        link.href = `${serverPath}/download/filePaths?filePaths=${encodeURIComponent(paths)}&currentPath=${encodeURIComponent(currentPath.value)}`;
        // 设置下载文件的名称
        link.download = 'download.zip';
        // 将虚拟元素追加到文档中
        document.body.appendChild(link);
        // 模拟点击这个虚拟链接以触发下载
        link.click();
        // 移除虚拟元素，清理文档
        document.body.removeChild(link);
    }

    function selected(row, column, rowIndex, columnIndex) {
        if (row.selected === true) {
            return {backgroundColor: "rgb(204, 232, 255)", color: "rgb(255,0,0)"}
        }
    }

    function uploadFile(formData) {
        formData.append('path', currentPath.value)
        uploadService.uploadFile(formData).then(res => {
            if (currentPath.value === uploadPath.value) {
                selectFilePath(currentPath.value)
            }
        })
    }

    function renameInput() {
        const find = tableData.value.find(item => item === rightRow);
        find.rename = true
    }

    async function fileRename() {
        await operateService.fileRename(rightRow.value.filePath, currentPath.value + "/" + rename.value)
        await selectFilePath(currentPath.value)
    }

    /**
     * 查询根目录
     * @returns {Promise<void>}
     */
    const selectRootPath = async () => {
        loading.value = true
        load++
        const res = await selectService.selectRootPath()
        tableData.value = []
        await showFileList(res, undefined)
    }

    /**
     * 查询文件夹下的文件
     * @param filePath
     * @returns {Promise<void>}
     */
    const selectFilePath = async (filePath) => {
        loading.value = true
        load++
        const res = await selectService.selectFilePath(filePath)
        currentPath.value = filePath
        pathCrumbs.value = currentPath.value.split("\\");
        tableData.value = []
        await showFileList(res, undefined);
    }

    /**
     * 点击表格一行元素
     * @param row
     * @param column
     * @param event
     * @returns {Promise<void>}
     */
    const clickRow = (row, column, event) => {
        if (column.label === "名称" && row.rename === false) {
            // 同时按下了 ctrl 键
            if (event.ctrlKey) {
                if (row.selected === undefined) {
                    row.selected = true
                } else {
                    row.selected = !row.selected
                }
            } else {
                // 只按下了鼠标左键
                selectFilePath(row.filePath)
            }
        }
    }

    /**
     * 显示文件列表
     * @param res
     * @param search 是否是搜索进入
     * @returns {Promise<void>}
     */
    async function showFileList(res, search) {
        let oldLoad = load.valueOf()
        loading.value = false

        tableData.value = res.data.data
        const map = new Map()
        for (let i = 0; i < tableData.value.length; i++) {
            if (oldLoad !== load) break;
            try {
                if (map.get(tableData.value[i].suffix) === undefined) {
                    const res1 = await previewService.previewIcon(tableData.value[i].filePath)
                    const blob = new Blob([res1.data], {type: 'image/png'})
                    if (oldLoad !== load) break;
                    const url = URL.createObjectURL(blob);
                    tableData.value[i].icon = url
                    if (tableData.value[i].suffix !== ".exe") {
                        map.set(tableData.value[i].suffix, url)
                    }
                } else {
                    tableData.value[i].icon = map.get(tableData.value[i].suffix)
                }
                tableData.value[i].rename = false
            } catch {
                ElMessage({
                    message: "图片加载失败",
                    type: "error"
                })
            }
        }
    }

    /**
     * 将路径分割成面包屑内容
     * @param index
     * @returns {Promise<void>}
     */
    async function selectPathCrumbs(index) {
        if (index === 0) {
            await selectRootPath()
        }
        if (pathCrumbs.value.length - 1 === index) return
        let filePath = ""
        for (let i = 0; i <= index; i++) {
            filePath += pathCrumbs.value[i] + "\\"
        }
        await selectFilePath(filePath)
    }

    async function selectName(name, size) {
        loading.value = true
        load++
        const res = await selectService.selectName(name, size)

        if (parseInt(res.data.msg) > searchMaxSize.value) {
            ElMessage({
                type: "warning",
                message: `共有 ${res.data.msg} 条数据,当前只展示 ${searchMaxSize.value} 条`
            })
        }

        tableData.value = []
        await showFileList(res, true)
    }

    /**
     * 右键元素
     * @param row
     * @param column
     * @param event
     */
    function rightClickRow(row, column, event) {
        row.selected = true
        event.preventDefault();

        const fileMenu = document.getElementById("file-menu");
        const x = event.clientX + window.pageXOffset;
        const y = event.clientY + window.pageYOffset;

        fileMenu.style.display = "block";
        fileMenu.style.position = "absolute";
        fileMenu.style.zIndex = "9999";
        fileMenu.style.top = y + "px";
        fileMenu.style.left = x + "px";

        rightRow.value = row
    }

    return {
        tableData, loading, pathCrumbs,
        searchName, searchMaxSize, currentPath,
        rightRow, rename, uploadFileList,
        uploadPath,
        selectRootPath, clickRow, selectFilePath,
        selectPathCrumbs, selectName, rightClickRow,
        fileRename, renameInput, uploadFile,
        selected,downloadFiles,

    }
})


